﻿Shader "Sample/Terrain"
{
    Properties
    {
		_Color ("Color", Color) = (1, 1, 1, 1)
        _MainTex ("Texture", 2D) = "white" {}
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 100

        Pass
        {
			Name "FORWARD"
			Tags {"LightMode" = "ForwardBase"}

            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"
			#include "Lighting.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
				float3 normal : NORMAL;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float4 vertex : SV_POSITION;
				float3 normal : NORMAL;
				float2 uv : TEXCOORD0;
				float4 shadowCoord : TEXCOORD1;
				float3 worldPos : TEXCOORD2;
            };

            sampler2D _MainTex;
            float4 _MainTex_ST;
			float4 _Color;
			uniform float4x4 _gWorldToShadow;
			uniform sampler2D _gShadowMapTexture;
			uniform float4 _gShadowMapTexture_ST;
			uniform float _gShadowStrength;

            v2f vert (appdata v)
            {
                v2f o;
				o.vertex = mul(unity_ObjectToWorld, v.vertex);
				o.worldPos = o.vertex.xyz;
				o.normal = normalize(mul(v.normal, unity_WorldToObject));
				o.shadowCoord = mul(_gWorldToShadow, o.vertex);
				o.vertex = UnityWorldToClipPos(o.vertex);
                o.uv = TRANSFORM_TEX(v.uv, _MainTex);
                return o;
            }

            fixed4 frag (v2f i) : COLOR0
            {
                fixed4 col = tex2D(_MainTex, i.uv) * _Color;

				i.shadowCoord.xy = i.shadowCoord.xy / i.shadowCoord.w;
				float2 uv = i.shadowCoord.xy;
				uv = uv * 0.5 + 0.5;

				float depth = i.shadowCoord.z / i.shadowCoord.w;
#if defined (SHADER_TARGET_GLSL)
				depth = depth * 0.5 + 0.5; //(-1, 1)-->(0, 1)
#elif defined (UNITY_REVERSED_Z)
				depth = 1 - depth;       //(1, 0)-->(0, 1)
#endif
				float4 shadowMapCol = tex2D(_gShadowMapTexture, uv);
				//float sampleDepth = DecodeFloatRGBA(shadowMapCol);
				float sampleDepth = shadowMapCol;
				float shadow = sampleDepth < depth ? _gShadowStrength : 1;
				
				float3 lightDir = UnityWorldSpaceLightDir(i.worldPos);
				float NoL = saturate(dot(normalize(i.normal), lightDir));
                return col * shadow * NoL;
            }
            ENDCG
        }
    	
    	
    }
	FallBack "Diffuse"//注意，整个Shader主要输出，如果出错，这里设置“跌落”到默认Shader，可能不是想要的结果
}
